<?php

namespace App\Http\Controllers;

use App\Models\Goods;
use App\Models\GoodsLike;
use Illuminate\Http\Request;

class GoodsLikeController extends Controller
{
    public function index(Request $request)
    {
        $data = GoodsLike::with(['user','goods'])->orderBy('status', 'asc')->paginate();
        return $this->response($data);
    }

    public function store(Request $request)
    {
        $obj = GoodsLike::where('user_id', $request->user()->id)->where('goods_id', $request->input('goods_id'))->first();
        if (is_object($obj)) {
            $obj->goods()->decrement('like');
            $obj->delete();
            return $this->response();
        } else {
            $obj = new GoodsLike();
            $goods = Goods::where('id', $request->input('goods_id'))->first();
            $obj->user_id = $request->user()->id;
            $obj->goods_id = $goods->id;
            $obj->save();
            $goods->increment('like');
            return $this->response();
        }
    }

    public function read(Request $request)
    {
        GoodsLike::where("id", 'in', $request->input('id'))->update(['status' => 1]);
        return $this->response();
    }
}
